<template>
  <div class="no-check-area">
    <c-table-box
      :table-height="350"
      class="area"
      checkbox
      hide-func
      :table-row-key="tableRowKeyFun"
      :click-row-selection="false"
      :data="showTableData"
      :table-span-method="tableSpanMethod"
      :table-config="tableConfig"
      @selection-change="selectionChange"
    >
      <template #btn>
        <AddArea style="margin-right:10px;" :filters-raw="filtersRaw" @on-change="changeHandle" />
        <AddStyle style="margin-right:10px;" :sel-data="selections" @on-change="changeStyleHandle" />
        <c-button type="primary" @click="removeHandle">删除</c-button>
      </template>
    </c-table-box>
  </div>
</template>
<script>
import AddArea from './addArea'
// import AddSeries from './addSeries'
import AddStyle from './addStyle'
import { otherFiltersItem } from '@/utils'
import { getUnSeriesByAccId } from '@/api/check'
const rttf = ['Q014', 'Q015']
export default {
  name: 'NoCheckArea',
  components: {
    AddArea,
    // AddSeries,
    AddStyle
  },
  data() {
    return {
      tableConfig: {
        interfacePath: '',
        pageFlag: false,
        setting: [
          {
            prop: 'areaName',
            label: '所属区域',
            minWidth: 120
          },
          {
            prop: 'spaceName',
            label: '所属空间',
            minWidth: 120,
            render: (h, row) => {
              return h('input-with-dialog', {
                props: {
                  value: [{ spaceCode: row.spaceCode, spaceName: row.spaceName }],
                  props: { label: 'spaceName', value: 'spaceCode' },
                  multiple: true,
                  focusQuery: true,
                  config: {
                    title: '所属空间',
                    width: '600px',
                    interfacePath: '/slm-admin/api/v1/configSpace/page',
                    method: 'post',
                    filtersRaw: [
                      // otherFiltersItem('enable', '1', '='),
                      otherFiltersItem('areaCode', row.areaCode, '='),
                      ...(row._groupArea || []).map(e => e.spaceCode).filter(e => !!e).map(e => otherFiltersItem('spaceCode', e, '<>'))
                    ],
                    paramsRaw: {},
                    setting: [
                      { prop: 'spaceCode', title: '编码', width: 80 },
                      { prop: 'spaceName', title: '名称', width: 200 }
                    ]
                  }
                },
                on: {
                  change: v => {
                    this.selectSpace(v, row)
                  }
                }
              })
            }
          },
          {
            prop: 'spaceAcceptArea',
            label: '验收面积',
            minWidth: 120,
            render: (h, row) => {
              if (this.isRTTF(row)) {
                return h('span', row.spaceAcceptArea)
              }
              return h('c-input-number', {
                props: {
                  placeholder: '请输入验收面积',
                  clearable: true,
                  value: row.spaceAcceptArea,
                  float: true
                },
                attrs: {
                  disabled: !row.spaceCode
                },
                on: {
                  input: v => {
                    this.$set(row, 'spaceAcceptArea', v)
                  },
                  change: (v) => {
                    this.syncValue(row, v, 'spaceAcceptArea', '_groupSpace')
                  }
                }
              })
            }
          },
          {
            prop: 'spaceAcceptDesc',
            label: '验收说明',
            minWidth: 120,
            render: (h, row) => {
              if (this.isRTTF(row)) {
                return h('span', row.spaceAcceptDesc)
              }
              return h('el-input', {
                props: {
                  placeholder: '请输入验收说明',
                  clearable: true,
                  value: row.spaceAcceptDesc,
                  disabled: !row.spaceCode
                },
                attrs: {
                  disabled: !row.spaceCode
                },
                on: {
                  input: v => {
                    this.$set(row, 'spaceAcceptDesc', v)
                  },
                  change: (v) => {
                    this.syncValue(row, v, 'spaceAcceptDesc', '_groupSpace')
                  }
                }
              })
            }
          },
          {
            prop: 'styleName',
            label: '所属专区',
            minWidth: 120
          },
          {
            prop: 'floors',
            label: '所在楼层',
            minWidth: 120,
            edit: {
              editType: 'text'
            }
          },
          {
            prop: 'styleAcceptArea',
            label: '验收面积',
            minWidth: 120,
            render: (h, row) => {
              if (!this.isRTTF(row)) {
                return h('span', row.styleAcceptArea)
              }
              return h('c-input-number', {
                props: {
                  placeholder: '请输入验收面积',
                  clearable: true,
                  value: row.styleAcceptArea,
                  float: true
                },
                attrs: {
                  disabled: !row.styleCode
                },
                on: {
                  input: v => {
                    this.$set(row, 'styleAcceptArea', v)
                  },
                  change: (v) => {
                    this.syncValue(row, v, 'styleAcceptArea', '_groupStyle')
                    this.sumSeriesToSpace(row)
                  }
                }
              })
            }
          },
          {
            prop: 'styleAcceptDesc',
            label: '验收说明',
            minWidth: 120,
            render: (h, row) => {
              if (!this.isRTTF(row)) {
                return h('span', row.styleAcceptDesc)
              }
              return h('el-input', {
                props: {
                  placeholder: '请输入验收说明',
                  clearable: true,
                  value: row.styleAcceptDesc,
                  disabled: !row.styleCode
                },
                attrs: {
                  disabled: !row.styleCode
                },
                on: {
                  input: v => {
                    this.$set(row, 'styleAcceptDesc', v)
                  },
                  change: (v) => {
                    this.syncValue(row, v, 'styleAcceptDesc', '_groupStyle')
                  }
                }
              })
            }
          },
          {
            prop: 'seriesName',
            label: '系列名称',
            minWidth: 120,
            render: (h, row) => {
              return h('input-with-dialog', {
                props: {
                  value: [{ seriesCode: row.seriesCode, seriesName: row.seriesName }],
                  props: { label: 'seriesName', value: 'seriesCode' },
                  multiple: true,
                  focusQuery: true,
                  disabled: !row.styleCode,
                  config: {
                    title: '系列名称',
                    width: '600px',
                    interfacePath: '/slm-admin/api/v1/configSeries/page',
                    method: 'post',
                    filtersRaw: [
                      // otherFiltersItem('enable', '1', '='),
                      otherFiltersItem('bigStyleCode', row.styleCode, '='),
                      otherFiltersItem('isPartakeSpread', '1', '='),
                      otherFiltersItem('areaCode', row.areaCode, '='),
                      ...(row._groupStyle || []).map(e => e.seriesCode).filter(e => !!e).map(e => otherFiltersItem('seriesCode', e, '<>'))
                    ],
                    paramsRaw: {},
                    setting: [
                      { prop: 'seriesCode', title: '编码', width: 80 },
                      { prop: 'seriesName', title: '名称', width: 200 }
                    ]
                  }
                },
                on: {
                  change: v => {
                    this.selectSeries(v, row)
                  }
                }
              })
            }
          }
        ]
      },
      rawTableData: [],
      addTableData: [],
      selections: []
    }
  },
  computed: {
    filtersRaw() {
      const t = this.showTableData.map(e => {
        return otherFiltersItem('areaCode', e.areaCode, '<>')
      })
      t.push(otherFiltersItem('enable', 1, '='))
      return t
    },
    showTableData() {
      return this.handleData([...this.rawTableData, ...this.addTableData])
    }
  },
  created() {
    this.getData()
  },
  methods: {
    isRTTF(row) {
      return rttf.includes(row.areaCode)
    },
    syncValue(row, v, targetKey, targetGroupKey) {
      const group = row[targetGroupKey] || []
      for (const r of group) {
        this.$set(r, targetKey, v)
      }
    },
    sum(row, key, groupKey) {
      const group = row[groupKey] || []
      let t = 0
      for (const r of group) {
        let n = Number(r[key])
        isNaN(n) ? n = 0 : ''
        t += n
      }
      return t
    },
    sumSeriesToSpace(row) {
      const gSpace = row._groupSpace || []
      const s = new Set()
      for (const sp of gSpace) {
        const gSeries = sp._groupStyle || []
        if (gSeries.length === 0) continue
        s.add(gSeries[0])
      }
      let t = 0
      Array.from(s).forEach(e => {
        const s = e.styleAcceptArea
        const n = Number(s)
        if (!isNaN(n))t += n
      })
      this.syncValue(row, t, 'spaceAcceptArea', '_groupSpace')
      return t
    },
    // 选择空间
    selectSpace(spaces, row) {
      const tmp = []
      spaces.forEach((space, i) => {
        if (i === 0 && !row.spaceCode) {
          this.$set(row, 'spaceCode', space.spaceCode)
          this.$set(row, 'spaceName', space.spaceName)
          this.$set(row, '_key', (Math.random() * 0xffff).toString(16))
          return
        }
        const t = this.removeUnderline({ ...row })
        const keys = `spaceAcceptArea spaceAcceptDesc styleName styleCode styleAcceptArea seriesName seriesCode`.split(' ')
        for (const k of keys) {
          t[k] = ''
        }
        t._key = (Math.random() * 0xffff).toString(16)
        t.spaceCode = space.spaceCode
        t.spaceName = space.spaceName
        tmp.push(t)
      })
      this.addTableData.push(...tmp)
    },
    // 专区变化
    changeStyleHandle(styles, row) {
      const tmp = []
      styles.forEach((style, i) => {
        if ((i === 0 && !row.styleCode) || styles.length === 1) {
          this.$set(row, 'styleCode', style.styleCode)
          this.$set(row, 'styleName', style.styleName)
          return
        }
        const t = this.removeUnderline({ ...row })
        const keys = `styleName styleCode styleAcceptArea seriesName seriesCode`.split(' ')
        for (const k of keys) {
          t[k] = ''
        }
        t._key = (Math.random() * 0xffff).toString(16)
        t.styleCode = style.styleCode
        t.styleName = style.styleName
        tmp.push(t)
      })
      this.addTableData.push(...tmp)
    },
    // 选择系列
    selectSeries(series, row) {
      if (series.length === 0) return
      const tmp = []
      series.forEach((serie, i) => {
        if ((i === 0 && !row.seriesCode) || serie.length === 1) {
          this.$set(row, 'seriesCode', serie.seriesCode)
          this.$set(row, 'seriesName', serie.seriesName)
          this.$set(row, '_key', (Math.random() * 0xffff).toString(16))
          return
        }
        const t = this.removeUnderline({ ...row })
        const keys = `seriesName seriesCode`.split(' ')
        for (const k of keys) {
          t[k] = ''
        }
        t._key = (Math.random() * 0xffff).toString(16)
        t.seriesCode = serie.seriesCode
        t.seriesName = serie.seriesName
        tmp.push(t)
      })
      // // 检测是否有重复
      // const hasAreaSpaceSerie = new Set()
      // hasAreaSpaceSerie.add(`${row.areaCode}-${row.spaceCode}-${row.styleCode}-${row.seriesCode}`)
      // this.showTableData.forEach(e => {
      //   if (e === row) return
      //   hasAreaSpaceSerie.add(`${e.areaCode}-${e.spaceCode}-${e.styleCode}-${e.seriesCode}`)
      // })
      // const repetition = []
      // console.log(hasAreaSpaceSerie, '============')
      // tmp.forEach(e => {
      //   if (hasAreaSpaceSerie.has(`${e.areaCode}-${e.spaceCode}-${e.styleCode}-${e.seriesCode}`)) {
      //     repetition.push(`${e.areaName}-${e.spaceName}-${e.styleName}-${e.seriesName}`)
      //   }
      // })
      // if (repetition.length > 0) {
      //   this.$message.warning(`【${repetition.join(',')}】组合重复！`)
      //   // this.$set(row, 'seriesCode', bakSeriesCode)
      //   // this.$set(row, 'seriesName', bakSeriesName)
      //   return
      // }
      this.addTableData.push(...tmp)
    },
    // 删除中间状态
    removeUnderline(obj) {
      for (const k of Object.keys(obj)) {
        if (/^_.+/.test(k)) {
          delete obj[k]
        }
      }
      return obj
    },
    // arg = {flag, index, groupKey, span}
    classifyFun(data, args) {
      const classify = {}
      const _args = [...args]
      const { flag, index, groupKey, span } = _args.shift()
      for (const item of data) {
        // 先清理数据，方便二次处理
        Object.keys(item).forEach(key => {
          if (/^_.+/.test(key) && key !== '_key') {
            delete item[key]
          }
        })
        const f = item[flag] === undefined ? flag : item[flag]
        // const i = item[index] === undefined ? 0 : item[index]
        // const key = `${f}@@${i}`
        const key = `${f}`
        if (classify[key] === undefined) {
          classify[key] = {
            list: [],
            groupKey: `_${groupKey}`,
            span: `_${span}`,
            index: `_${index}`,
            order: item[index]
          }
        }
        if (classify[key].order === undefined) {
          classify[key].order = item[index]
        }
        classify[key].list.push(item)
      }
      if (_args.length > 0) {
        Object.values(classify).forEach(e => {
          e.classify = this.classifyFun(e.list, _args)
        })
      }
      return classify
    },
    handleData(data) {
      // 按区域分类
      const args = [
        { flag: 'areaCode', index: 'areaIndex', groupKey: 'groupArea', span: 'areaRowSpan' },
        { flag: 'spaceCode', index: 'spaceIndex', groupKey: 'groupSpace', span: 'spaceRowSpan' },
        { flag: 'styleCode', index: 'styleIndex', groupKey: 'groupStyle', span: 'styleRowSpan' }
      ]
      const area = this.classifyFun(data, args)
      // 排序函数
      const sort = (data, order = 'asc') => {
        const t = Object.entries(data)
        const l = t.length
        for (let i = 0; i < l; i++) {
          for (let m = i + 1; m < l; m++) {
            const a = t[i]
            // let i1 = Number(a[0].split('@@')[1])
            let i1 = Number(a[1].order)
            if (isNaN(i1)) { i1 = 0 }
            const b = t[m]
            // let i2 = Number(b[0].split('@@')[1])
            let i2 = Number(b[1].order)
            if (isNaN(i2)) { i2 = 0 }
            if (order === 'asc' && i1 > i2) {
              t.splice(i, 1, b)
              t.splice(m, 1, a)
            } else if (order === 'desc' && i1 < i2) {
              t.splice(i, 1, b)
              t.splice(m, 1, a)
            }
          }
        }
        return t
      }
      const result = []
      const collectFun = (data) => {
        const arrs = sort(data)
        arrs.forEach(e => {
          const t = e[1]
          // eslint-disable-next-line no-unused-vars
          const { list, classify, groupKey, span } = t
          list.forEach((e, i) => {
            e[groupKey] = list
          })
          if (classify) {
            collectFun(classify)
          } else {
            // 系列
            list.sort((a, b) => {
              const a1 = Number(a.seriesCode || 0)
              const b1 = Number(b.seriesCode || 0)
              return b1 - a1
            })
            result.push(...list)
          }
        })
      }
      collectFun(area)
      result.forEach((e, i) => {
        const merge = (row, flag, span, groupKey) => {
          if (row[flag]) return
          const list = row[groupKey]
          if (row[flag] === undefined) {
            list.forEach(e => {
              e[flag] = true
              e[span] = 0
            })
            row[span] = list.length
          }
        }
        if (e.unique_key === undefined) {
          e.unique_key = (Math.random() * 0xffff).toString(16)
        }
        merge(e, '_areaMerge', '_areaRowSpan', '_groupArea')
        merge(e, '_spaceMerge', '_spaceRowSpan', '_groupSpace')
        merge(e, '_styleMerge', '_styleRowSpan', '_groupStyle')
        'isProgramOutpic isDetailOutpic isAccept'.split(' ').forEach(k => {
          if (e[k] === undefined || e[k] === 0) {
            e[k] = '0'
          }
        })
      })
      return result
    },
    tableRowKeyFun(row) {
      return row.unique_key
    },
    // 选择区域
    changeHandle(v) {
      if (v.length === 0) return
      v = v.map(e => {
        return {
          acceptId: this.$route.query.id, //	门店验收ID
          actualOutpicArea: '', //	空间出图面积
          areaCode: e.areaCode, //	所属区域编码
          areaName: e.areaName, //	所属区域名称
          assortAcceptArea: '', //	配套定制验收面积
          chooseCupboardSeriesCode: '', //	配套橱柜系列编码
          chooseCupboardSeriesName: '', //	配套橱柜系列名称
          assortCustomizedArea: '', //	配套定制出图面积
          chooseCustomizedSeriesCode: '', //	配套定制系列编码
          chooseCustomizedSeriesName: '', //	配套定制系列名称
          id: '', //	ID
          isAccept: '0', //	是否验收 0否 1是
          isDetailOutpic: '0', //	是否系列出图：0否1是
          isProgramOutpic: '0', //	空间是否出图：0否1是
          seriesCode: '', //	系列编码
          seriesName: '', //	系列名称
          spaceAcceptArea: '', //	空间验收面积
          spaceAcceptDesc: '', //	空间验收说明
          spaceCode: '', //	所属空间编码
          spaceName: '', //	所属空间名称
          styleAcceptArea: '', //	专区验收面积
          styleAcceptDesc: '', //	专区验收说明
          styleActualOutpicArea: '', //	专区出图面积
          styleCode: '', //	专区编码
          styleName: '', //	专区名称
          floors: undefined,
          types: 0 //	是否本次验收：0否1是
        }
      })
      this.addTableData.unshift(...v)
    },
    tableSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 区域
      if ([2].includes(columnIndex)) {
        return [row._areaRowSpan, 1]
      }
      // 空间
      if ([3, 4, 5].includes(columnIndex)) {
        return [row._spaceRowSpan, 1]
      }
      if ([6, 7, 8].includes(columnIndex)) {
        return [row._styleRowSpan, 1]
      }
      return [1, 1]
    },
    selectionChange(v) {
      this.selections = v
    },
    // 删除
    removeHandle() {
      if (!this.singleJudge(this.selections, '删除')) {
        return
      }
      this.rawTableData = this.rawTableData.filter(e => {
        return !this.selections.includes(e)
      })
      this.addTableData = this.addTableData.filter(e => {
        return !this.selections.includes(e)
      })

      this.selections = []
      this.$nextTick(() => {
      // 重新计算验收面积
        const t = {}
        for (const r of this.showTableData) {
          t[r.spaceCode] = r
        }
        for (const r of Object.values(t)) {
          if (this.isRTTF(r)) {
            this.sumSeriesToSpace(r)
          }
        }
      })
    },
    // 获取详情
    getData() {
      const { id } = this.$route.query
      getUnSeriesByAccId(id).then(res => {
        this.rawTableData = this.handleData(res.data)
      })
    },
    // 校验数据
    validate(isPromise = true) {
      const result = []
      const msg = (a, i, b) => {
        let m = typeof i === 'number' ? `${a}第${i + 1}行${b}!` : `${a}${i}${b}!`
        m = `非本次验收：${m}`
        this.$message.warning(m)
        return isPromise ? Promise.reject(m) : false
      }
      for (let i = 0; i < this.showTableData.length; i++) {
        const v = { ...this.showTableData[i] }
        Object.keys(v).forEach(key => {
          if (/^_.+/.test(key) || key === 'unique_key') {
            delete v[key]
          }
        })
        if (!v.spaceCode) {
          return msg('请选择', i, '所属空间')
        }
        if (rttf.includes(v.areaCode)) {
          if (v.styleCode) {
            if (!this.$gtZero(v.styleAcceptArea)) {
              return msg('请填写【', v.styleName, '】验收面积')
            }
          }
        } else {
          if (!this.$gtZero(v.spaceAcceptArea)) {
            return msg('请填写【', v.spaceName, '】验收面积')
          }
        }
        result.push(v)
      }
      return isPromise ? Promise.resolve(result) : result
    }
  }
}
</script>
<style lang="scss" scoped>
.no-check-area{
  .area{
    & /deep/ .el-table__row{
      background-color: #fff !important;
    }
    & /deep/ .hover-row{
      background-color: #fff !important;
    }
    & /deep/ td{
      background-color: #fff !important;
    }
  }
}
</style>
